package com.cracker.sso.interceptor;

import com.cracker.sso.model.TokenModel;
import com.cracker.sso.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String redirect = request.getParameter("oauth_callback");
        // TODO 检查redirect是否合法
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                //获取TGT（Ticket Granting Ticket）是存储在TGCcookie中的代表用户的SSO会话。
                if (cookie.getName().equalsIgnoreCase("TGT-COOKIE")) {
                    // 读取token是否失效,避免重复登录
                    String token = cookie.getValue();
                    TokenModel tokenModel = tokenService.get(token);
                    // 携带token跳回应用站
                    if (null != tokenModel) {
                        response.sendRedirect(String.format("%s?token=%s", redirect, token));
                    }
                }
            }
        }
        return true;
    }
}
